import { useRequest } from 'alova/client'
import {
  Card,
  Form,
  Input,
  Button,
  Select,
  App,
  Cascader,
  CascaderProps,
  Row,
  Col,
  Space,
} from 'antd'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'
import { UserOpenAccountDataVO } from '../api/globals'

const { Item } = Form
const { Option } = Select

const OrderAdd: React.FC = () => {
  const [form] = Form.useForm<UserOpenAccountDataVO>()
  const { message } = App.useApp()
  const navigate = useNavigate()

  const { data: productList, send: fetchProductList } = useRequest(
    () => Apis.cm.Product({}),
    {
      immediate: false,
    }
  )

  const { data: districtList, send: fetchDistrictList } = useRequest(
    () => Apis.cm.District({}),
    {
      immediate: false,
    }
  )

  const onDistrictAndStreetChange: CascaderProps['onChange'] = (
    selectedOptions,
    selectedOptionsLabels
  ) => {
    const districtId = selectedOptions[0]
    const streetId = selectedOptions[1]
    if (districtId && streetId) {
      form.setFieldsValue({
        addressDistrict: districtId as string,
        addressStreet: streetId as string,
        addressDistrictName: selectedOptionsLabels[0].label as string,
        addressStreetName: selectedOptionsLabels[1].label as string,
      })
    }
  }

  useEffect(() => {
    fetchProductList()
    fetchDistrictList()
  }, [])

  const handleSubmit = () => {
    form
      .validateFields()
      .then((values) => {
        Apis.apply
          .Do({
            data: {
              ...values,
            },
          })
          .then(() => {
            message.success('创建成功')
            navigate('/list')
          })
          .catch((err) => {
            console.log('err', err)
            message.error('创建失败')
          })
      })
      .catch((err) => {
        console.log('err', err)
        const { errorFields } = err
        if (errorFields) {
          for (const field of errorFields) {
            const { errors } = field
            if (errors.length > 0) {
              const errorMessage = errors[0]
              message.error(errorMessage)
            }
          }
        }
      })
  }

  return (
    <div className="pl-8 pr-8 flex flex-col justify-start items-center">
      <Card
        title="创建工单"
        extra={<Button onClick={() => navigate('/list')}>返回</Button>}
        className="max-w-7xl mx-auto"
      >
        <Form form={form} layout="vertical">
          <Row gutter={[24, 0]}>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item
                label="用户姓名"
                name="name"
                rules={[{ required: true, message: '请输入用户姓名' }]}
              >
                <Input placeholder="请输入用户姓名" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item
                label="用户手机号"
                name="phone"
                rules={[{ required: true, message: '请输入用户手机号' }]}
              >
                <Input placeholder="请输入用户手机号" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="用户身份证号" name="idcard">
                <Input placeholder="请输入用户身份证号" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="固定电话" name="telephone">
                <Input placeholder="请输入固定电话" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item
                label="产品"
                name="productId"
                rules={[{ required: true, message: '请选择产品' }]}
              >
                <Select placeholder="请选择产品">
                  {productList?.map((product) => (
                    <Option key={product.id} value={product.id}>
                      {product.name}
                    </Option>
                  ))}
                </Select>
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item
                label="区划"
                name="district"
                rules={[{ required: true, message: '请选择区划' }]}
              >
                <Cascader
                  placeholder="请选择区划"
                  options={districtList?.sub?.map((district) => ({
                    value: district.id,
                    label: district.name,
                    children: district.sub?.map((street) => ({
                      value: street.id,
                      label: street.name,
                    })),
                  }))}
                  onChange={onDistrictAndStreetChange}
                />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={24} lg={24} xl={24}>
              <Item
                label="详细地址"
                name="address"
                rules={[{ required: true, message: '请输入详细地址' }]}
              >
                <Input placeholder="请输入详细地址" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="电子邮箱" name="email">
                <Input placeholder="请输入电子邮箱" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="自来水户号" name="waterHostCode">
                <Input placeholder="请输入自来水户号" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="自来水户名" name="waterHostName">
                <Input placeholder="请输入自来水户名" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="被委托人姓名" name="commissionName">
                <Input placeholder="请输入被委托人姓名" />
              </Item>
            </Col>
            <Col xs={24} sm={24} md={12} lg={12} xl={12}>
              <Item label="被委托人身份证号" name="commissionIdcard">
                <Input placeholder="请输入被委托人身份证号" />
              </Item>
            </Col>
          </Row>

          {/* 隐藏字段，用于存储区划和街道信息 */}
          <Item name="addressDistrict" hidden={true}></Item>
          <Item name="addressStreet" hidden={true}></Item>
          <Item name="addressDistrictName" hidden={true}></Item>
          <Item name="addressStreetName" hidden={true}></Item>

          <Item className="flex justify-center mt-6">
            <Space size="middle">
              <Button type="primary" onClick={handleSubmit}>
                提交
              </Button>
              <Button onClick={() => navigate('/order/list')}>取消</Button>
            </Space>
          </Item>
        </Form>
      </Card>
    </div>
  )
}

export default OrderAdd
